import time
import random

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.app01.models import Order, Product, ProductCount, Address, User
from .serializers import OrderCreateSerializer

class CreateOrderView(APIView):

    def post(self, request, *args, **kwargs):
        # 第一步：反序列化并校验前端提交的数据
        serializer = OrderCreateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 获取校验后的数据
        address_id = serializer.validated_data['addressId']
        total_price = serializer.validated_data['totalPrice']
        products_data = serializer.validated_data['products']

        # 第二步：获取当前登录用户 (此处假设已做登录认证，并可从 request.user 中获取)
        user_id = request.user['user_id']
        user = User.objects.get(id=user_id)
        # if user.is_anonymous:
        #     return Response({"code": 0, "message": "用户未登录"}, status=status.HTTP_401_UNAUTHORIZED)
        # user = User.objects.get(id=1)

        # 第三步：查询收货地址，若要保证用户只能使用自己的地址，可额外加上 user=user 判断
        try:
            address = Address.objects.get(id=address_id, user=user_id)
        except Address.DoesNotExist:
            return Response({"code": 0, "message": "地址不存在"}, status=status.HTTP_400_BAD_REQUEST)

        # 第四步：创建订单主表信息
        # 订单ID通常可自定义生成，示例中简单使用时间戳+随机数
        order_id = f"{int(time.time()*1000)}{random.randint(1000,9999)}"
        order_status = 1  # 1=待付款

        order_obj = Order.objects.create(
            order_id=order_id,
            user=user,
            payment=total_price,
            status=order_status,
            name=address.name,
            phone=address.phone,
            dz=address.dz
        )

        # 第五步：创建 ProductCount 对象，并添加到 Order 的多对多关系
        product_count_list = []
        for item in products_data:
            product_id = item.get('productId')
            price = item.get('price')
            count = item.get('count')
            config = item.get('config', [])

            # 查找对应产品
            try:
                product = Product.objects.get(id=product_id)
            except Product.DoesNotExist:
                # 找不到产品，可根据业务需求决定是否报错 或跳过
                return Response({"code": 0, "message": f"ID为 {product_id} 的产品不存在"},
                                status=status.HTTP_400_BAD_REQUEST)

            # 创建 ProductCount
            product_count = ProductCount.objects.create(
                product=product,
                price=price,
                count=count,
                selected_configs=config  # 直接存储前端传来的配置信息
            )
            product_count_list.append(product_count)

        # 将所有创建的 ProductCount 添加到 Order 的 M2M 字段
        order_obj.products.add(*product_count_list)

        # 第六步：返回响应
        return Response({
            "code": 1,
            "message": "ok",
            "data": {
                "id": order_id,
                "status": order_status
            }
        }, status=status.HTTP_201_CREATED)
